import { useState } from 'react'
import { View, Text } from '@tarojs/components'
import { Cell, Field, Button, Tabs, Input, Radio } from '@taroify/core'
import Taro, { useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import './index.scss'

// 长度单位换算
const lengthUnits = {
  mm: { name: '毫米', factor: 0.001 },
  cm: { name: '厘米', factor: 0.01 },
  m: { name: '米', factor: 1 },
  km: { name: '千米', factor: 1000 },
  inch: { name: '英寸', factor: 0.0254 },
  foot: { name: '英尺', factor: 0.3048 },
  yard: { name: '码', factor: 0.9144 },
  mile: { name: '英里', factor: 1609.34 }
}

// 重量单位换算
const weightUnits = {
  mg: { name: '毫克', factor: 0.001 },
  g: { name: '克', factor: 1 },
  kg: { name: '千克', factor: 1000 },
  t: { name: '吨', factor: 1000000 },
  oz: { name: '盎司', factor: 28.3495 },
  lb: { name: '磅', factor: 453.592 }
}

// 面积单位换算
const areaUnits = {
  sqm: { name: '平方米', factor: 1 },
  sqkm: { name: '平方千米', factor: 1000000 },
  ha: { name: '公顷', factor: 10000 },
  sqft: { name: '平方英尺', factor: 0.092903 },
  sqyd: { name: '平方码', factor: 0.836127 },
  acre: { name: '英亩', factor: 4046.86 },
  mu: { name: '亩', factor: 666.67 }
}

// 体积单位换算
const volumeUnits = {
  ml: { name: '毫升', factor: 0.001 },
  l: { name: '升', factor: 1 },
  cubicm: { name: '立方米', factor: 1000 },
  floz: { name: '液量盎司', factor: 0.0295735 },
  cup: { name: '杯', factor: 0.24 },
  pint: { name: '品脱', factor: 0.473176 },
  gallon: { name: '加仑', factor: 3.78541 }
}

// 类别映射
const categoryMap = [
  { name: '长度', units: lengthUnits, defaultFrom: 'm', defaultTo: 'cm' },
  { name: '重量', units: weightUnits, defaultFrom: 'kg', defaultTo: 'g' },
  { name: '面积', units: areaUnits, defaultFrom: 'sqm', defaultTo: 'mu' },
  { name: '体积', units: volumeUnits, defaultFrom: 'l', defaultTo: 'ml' }
]

const UnitConverter = () => {
  const [activeTab, setActiveTab] = useState(0)
  const [inputValue, setInputValue] = useState('')
  const [fromUnit, setFromUnit] = useState(categoryMap[0].defaultFrom)
  const [toUnit, setToUnit] = useState(categoryMap[0].defaultTo)
  const [result, setResult] = useState('')

  // 分享给朋友
  useShareAppMessage(() => {
    return {
      title: '这款单位换算工具太方便了！一键搞定所有换算难题🚀',
      path: '/pages/unit-converter/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: '这款单位换算工具太方便了！一键搞定所有换算难题🚀',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  const handleTabChange = (index) => {
    // Taroify的Tabs组件onChange只传递index参数
    setActiveTab(index)
    // 确保index在有效范围内
    if (index >= 0 && index < categoryMap.length) {
      setFromUnit(categoryMap[index].defaultFrom)
      setToUnit(categoryMap[index].defaultTo)
      setInputValue('')
      setResult('')
    }
  }

  const handleConvert = () => {
    if (!inputValue || Number.isNaN(Number(inputValue))) {
      Taro.showToast({
        title: '请输入有效数字',
        icon: 'none'
      })
      return
    }

    const currentUnits = categoryMap[activeTab]?.units
    if (!currentUnits) {
      Taro.showToast({
        title: '单位类型无效',
        icon: 'none'
      })
      return
    }

    const fromFactor = currentUnits[fromUnit]?.factor
    const toFactor = currentUnits[toUnit]?.factor

    if (!fromFactor || !toFactor) {
      Taro.showToast({
        title: '请选择有效的单位',
        icon: 'none'
      })
      return
    }

    // 先转换为基本单位，再转换为目标单位
    const baseValue = parseFloat(inputValue) * fromFactor
    const resultValue = baseValue / toFactor

    // 格式化结果，移除末尾多余的零
    const formatResult = (num) => {
      // 先保留6位小数
      const fixed = num.toFixed(6)
      // 转回浮点数会自动去掉末尾的0
      return parseFloat(fixed)
    }

    setResult(formatResult(resultValue).toString())
  }

  // 安全获取当前单位
  const currentUnits = categoryMap[activeTab]?.units || {}

  return (
    <View className='unit-converter'>
      <View className='converter-header'>
        <Text className='header-title'>单位换算工具</Text>
      </View>

      <Tabs value={activeTab} onChange={handleTabChange}>
        {categoryMap.map((category, index) => (
          <Tabs.TabPane key={index} title={category.name} />
        ))}
      </Tabs>

      <View className='converter-container'>
        <Cell.Group inset title='换算设置'>
          <Field label='数值'>
            <Input
              type='digit'
              placeholder='请输入数值'
              value={inputValue}
              onChange={(e) => setInputValue(e.detail.value)}
            />
          </Field>

          <Field label='从'>
            <Radio.Group value={fromUnit} direction='horizontal' onChange={setFromUnit}>
              <View className='radio-container'>
                {Object.keys(currentUnits || {}).map((unit) => (
                  <Radio key={unit} name={unit}>
                    {currentUnits[unit]?.name || unit}
                  </Radio>
                ))}
              </View>
            </Radio.Group>
          </Field>

          <Field label='到'>
            <Radio.Group value={toUnit} direction='horizontal' onChange={setToUnit}>
              <View className='radio-container'>
                {Object.keys(currentUnits || {}).map((unit) => (
                  <Radio key={unit} name={unit}>
                    {currentUnits[unit]?.name || unit}
                  </Radio>
                ))}
              </View>
            </Radio.Group>
          </Field>
        </Cell.Group>

        <View className='button-container'>
          <Button color='primary' block onClick={handleConvert}>
            开始换算
          </Button>
        </View>

        {result && (
          <View className='result-container'>
            <Cell.Group inset title='换算结果'>
              <Cell>
                <View className='result-content'>
                  <Text className='result-label'>
                    {inputValue} {currentUnits[fromUnit]?.name || fromUnit} 等于:
                  </Text>
                  <View className='result-value-container'>
                    <Text className='result-text'>
                      {result} {currentUnits[toUnit]?.name || toUnit}
                    </Text>
                  </View>
                </View>
              </Cell>
            </Cell.Group>
          </View>
        )}
      </View>
    </View>
  )
}

export default UnitConverter
